﻿using Md.Api.Model.Util.Upload.Request;
using Microsoft.AspNetCore.Http;
using Md.Api.DDD;

namespace Md.Api.Service.Util.Upload;
/// <summary>
/// 本地单文件上传服务
/// </summary>
public class LocalSingleUploadService : ApiBase<RequestLocalSingleUploadModel>
{
    /// <summary>
    /// 执行
    /// </summary>
    /// <exception cref="NotImplementedException"></exception>
    protected override void ExecuteMethod()
    {
        if (Parameter.Form == null || Parameter.Form.Files == null || Parameter.Form.Files.Count == 0)
        {
            throw new AggregateException("请选择文件");
        }

        // 文件夹名称
        var dirName = DateTime.Now.ToString("yyyyMMdd");

        var fileName = $"{Guid.NewGuid().ToString().Replace("-", "")}{DateTime.Now.ToString("yyyyMMddHHmmssffff")}";

        var tempFileFolder = Path.Combine(FileBasePath, dirName);

        if (!Directory.Exists(tempFileFolder))
        {
            Directory.CreateDirectory(tempFileFolder);
        }

        IFormFile? file = Parameter.Form.Files[0];

        // 获取文件扩展名
        var fileNameArr = file.FileName.Split(".");
        var ext = fileNameArr[fileNameArr.Length - 1];

        // 文件流读取
        var stream = file.OpenReadStream();
        byte[] bytes = new byte[stream.Length];
        stream.Read(bytes, 0, bytes.Length);

        // 文件位于服务器地址
        var localFileFullPath = Path.Combine(tempFileFolder, $"{fileName}.{ext}");

        // 保存文件
        var fileStream = new FileStream(localFileFullPath, FileMode.Create);

        file.CopyTo(fileStream);

        fileStream.Flush();
        fileStream.Close();
        fileStream.Dispose();

        var res = new { localFileFullPath, localFilePath = $"{dirName}/{fileName}.{ext}", url = $"{JsonConfig.JsonRead("MdSettings:MdFileDomain")}/{dirName}/{fileName}.{ext}", fileName, ext, originalFileName = file.FileName };

        Result.Data = res;
        Result.Msg = "success";
    }
}
